package com.graduation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.mapper.SearchHistoryMapper;
import com.graduation.pojo.po.SearchHistory;
import com.graduation.service.SearchHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SearchHistoryServiceImpl extends ServiceImpl<SearchHistoryMapper, SearchHistory> implements SearchHistoryService {

    @Override
    public List<SearchHistory> getUserSearchHistory(Long userId) {
        LambdaQueryWrapper<SearchHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchHistory::getUserId, userId)
                   .orderByDesc(SearchHistory::getSearchTime);
        return list(queryWrapper);
    }

    @Override
    public void addSearchHistory(Long userId, String query) {
        // 检查当前用户的搜索记录数量
        LambdaQueryWrapper<SearchHistory> countWrapper = new LambdaQueryWrapper<>();
        countWrapper.eq(SearchHistory::getUserId, userId);
        countWrapper.eq(SearchHistory::getQuery, query);
        long count = count(countWrapper);
        
        // 如果已经有20条记录，删除最早的一条
        if (count >= 20) {
            LambdaQueryWrapper<SearchHistory> oldestWrapper = new LambdaQueryWrapper<>();
            oldestWrapper.eq(SearchHistory::getUserId, userId)
                        .orderByAsc(SearchHistory::getSearchTime)
                        .last("LIMIT 1");
            SearchHistory oldest = getOne(oldestWrapper);
            if (oldest != null) {
                removeById(oldest.getId());
            }
        }
        
        // 添加新的搜索记录
        SearchHistory searchHistory = new SearchHistory()
                .setUserId(userId)
                .setQuery(query)
                .setSearchTime(LocalDateTime.now());
        save(searchHistory);
        
        log.info("用户 {} 添加搜索记录: {}", userId, query);
    }
}
